import { componentRegistry } from './ComponentRegistry'
import type { CommandRegistryItem, CommandResult, CommandContext } from './types/core'

class CommandRegistry {
  private commands = new Map<string, CommandRegistryItem>()

  /**
   * 注册新命令
   */
  register(item: CommandRegistryItem) {
    if (this.commands.has(item.meta.id)) {
      console.warn(`Command '${item.meta.id}' is already registered.`)
      return
    }

    this.commands.set(item.meta.id, item)
    console.debug(`Command registered: ${item.meta.id}`)
  }

  /**
   * 执行命令
   */
  async execute(commandId: string, args: any, context: CommandContext): Promise<CommandResult> {
    const command = this.commands.get(commandId)
    if (!command) {
      return {
        success: false,
        message: `Command not found: ${commandId}`,
      }
    }

    try {
      const result = await command.execute(
        {
          ...context,
          componentRegistry,
        },
        args,
      )

      return result
    } catch (error: any) {
      console.error(`Command execution failed: ${commandId}`, error)
      return {
        success: false,
        message: error.message || 'Unknown error during command execution',
      }
    }
  }

  /**
   * 按ID获取命令
   */
  getCommand(commandId: string): CommandRegistryItem | null {
    return this.commands.get(commandId) || null
  }
}

// 导出全局单例
export const commandRegistry = new CommandRegistry()
